const { mutations, actions } = require("./num")
//购物车vuex的业务逻辑
//  import goodsApi from '../api/goodsApi';

let cart = {
    state : {
        cartList : []
    },

    getters:{
        //显示购物车总数量
        total(state) {
            return state.cartList.length;
        }
    },

    mutations:{//操纵本地数据：state
        //设置购物车数据
        setCartList(state,data) {
            state.cartList = data;
        },

        addItem(state,data) {
            state.cartList.push(data);
        },

        editItem(state,{index,data}) {
            state.cartList[index] = data;
        },

        del(state,id) {
            state.cartList = state.cartList.filter(item => item.id != id);
        },

        dels(state,data) {
            data.forEach(id => {
                state.cartList = state.cartList.filter(item => item.id != id);
            })
        }
    },

    actions : {//操纵远程数据
        //功能：发请求  首页：this.$store.dispatch('getList') 购物车：this.$store.state.cart.cartList
        getList({commit},{page,pageSize}) {
            
            goodsApi.getList(page,pageSize).then(res => {
                if(res.data.flag) {
                    //获取数据：存放到state
                    commit('setCartList',res.data.data);
                }
            })
        },

        //功能：添加新订单   详情页：this.$store.dispatch('addGood',data)
        addGood({commit},payload) {
            goodsApi.addGood(payload).then(res => {
                if(res.data.flag) {
                    //新增成功
                    commit('addItem',res.data.data);
                }else{
                    //修改成功
                    commit('editItem',{index,data:res.data})
                }
            })
        },

        //功能：删除某个商品  购物车页：this.$store.dispatch('removeGood',data)
        removeGood({commit},id) {
            goodsApi.del(id).then(res => {
                if(res.data.flag) {
                    commit('del',id);
                }
            })
        },

        //功能：删除多条
        removeMany({commit},data) {
            //data ['id1','id2']
            goodsApi.dels(data).then(res => {
                if(res.data.flag) {
                    commit('dels',data);
                }
            })
        },

    }
}

module.exports = cart;